/*
*   action模块
* */

import {reqAddress,reqCategory,reqShops,requSerLogin,reqLogout,reqInfo,reqGoods,reqRatings,reqShopsImg} from '../api'
import {RECEIVE_ADDRESS,RECEIVE_CATEGORY,RECEIVE_SHOPS,RECEIVE_USERLOGIN,RECEIVE_LOGOUT,RECEIVE_INFO,RECEIVE_GOODS,RECEIVE_RATINGS,RECTIVE_SHOPSIMG,INCREMENT_FOOD_COUNT,DECREMENT_FOOD_COUNT} from './mutation-type'

export default {
  //异步获取地址
  async getAddress({commit,state}){
    const hoh = state.latitude + ',' + state.longitude
    const result =  await reqAddress(hoh)
    if(result.code == 0){
      const address = result.data;
      commit(RECEIVE_ADDRESS,{address})
    }
  },
  //异步获取分类
  async getCategory({commit}){
    const result = await reqCategory()
    if(result.code == 0){
      const category = result.data;
      commit(RECEIVE_CATEGORY,{category})
    }
  },
  //异步获取商家
  async getShops({commit,state}){
    //发送ajax请求
    const {latitude,longitude} = state
    const result = await reqShops({latitude,longitude})
    //提交一个mutation
    if(result.code == 0){
      const shops = result.data;
      commit(RECEIVE_SHOPS,{shops});
    }
  },
  //同步获取用户
  setLogin({commit},userLogin){
    commit(RECEIVE_USERLOGIN,{userLogin})
  },
  //异步获取用户
  async getUserLogin ({commit}){
    const result = await requSerLogin();
    if(result.code === 0){
      commit(RECEIVE_USERLOGIN,{userLogin: result.data})
    }
  },
  //退出登陆
  async getLogout ({commit}){
    const result = await reqLogout()
    if(result.code === 0){
      commit(RECEIVE_LOGOUT)
    }
  },
  //异步获取商家头部信息
  async getInfo ({commit}){
    const result = await reqInfo();
    if(result.code === 0){
      commit(RECEIVE_INFO,{info:result.data})
    }
  },
  //异步获取商家商品信息
  async getGoods ({commit} , fn){
    const result = await reqGoods();
    if(result.code === 0){
      commit(RECEIVE_GOODS,{goods:result.data});
      fn && fn()
    }
  },
  //异步获取用户评价信息
  async getRatings ({commit}){
    const result = await reqRatings();
    if(result.code === 0){
      commit(RECEIVE_RATINGS,{ratings: result.data});
    }
  },
  //异步获取商家图片
  async getShopsImg ({commit}){
    const result = await reqShopsImg();
    if(result.code === 0){
      commit(RECTIVE_SHOPSIMG,{shopsImg: result.data})
    }
  },
  //同步count组件数值
  getAddCommodityCount ({commit},{isCount,foods}){
    if(!isCount){
      commit(DECREMENT_FOOD_COUNT,{foods})
    }else{
      commit(INCREMENT_FOOD_COUNT,{foods})
    }
  }
}

